package com.GraduationDesign.backend.utils;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;

import javax.validation.constraints.NotEmpty;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author DestinyCc
 */
public class SnowFlakeUtil {

    private static final String serverPrefix = "sv";
    private static Integer workerId = 0;
    private static Integer datacenterId = 0;
    private static final String[] DATACENTERS = {"sh2"};

    private static final Map<String, Integer> AppName2DatacenterMap = new HashMap<String, Integer>() {{
        put("auth-service", 1);
        put("gateway", 2);
        put("diff-service", 3);
    }};

    /**
     * 派号器workid：0~31 机房datacenterid：0~31
     */
    private static Snowflake snowflake;


    public static void initSnowflake(String appName) {
        try {
            String hostName = InetAddress.getLocalHost().getHostName();
            workerId = getWorkerId(hostName);
            datacenterId = getDatacenterId(hostName);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        snowflake = IdUtil.createSnowflake(workerId, datacenterId);
    }

    /**
     * sv1sh2: 1-worker, sh2-datacenter
     */
    public static Integer getWorkerId(@NotEmpty String name) {
        if (!name.startsWith(serverPrefix)) {
            return 0;
        }
        final int begin = serverPrefix.length();
        int end = begin;
        while (end < name.length()) {
            char c = name.charAt(end);
            if (!Character.isDigit(c)) {
                break;
            }
            end++;
        }
        if (end > begin) {
            return Integer.valueOf(name.substring(begin, end));
        }
        return 0;
    }

    /**
     * sv1sh2: 1-worker, sh2-datacenter
     */
    public static Integer getDatacenterId(@NotEmpty String name) {
        for (int i = 0; i < DATACENTERS.length; i++) {
            if (name.endsWith(DATACENTERS[i])) {
                return i + 1;
            }
        }
        return 0;
    }


    public static Integer getDatacenterIdByAppName(@NotEmpty String appName) {
        Integer datacenter = AppName2DatacenterMap.get(appName);
        return Objects.isNull(datacenter) ? 0 : datacenter;
    }

    public static Long nextId() {
        return snowflake.nextId();
    }

}
